<template>
  <!-- 头像上传的组件，实现图片的选择预览 -->
  <div class="uploader">
    <label for="file" class="uploadFileClass">
      <div><img class="myimg" id="myimg" src="@/assets/logo.png" alt="" /></div>
    </label>
    <input
      type="file"
      id="file"
      style="display: none"
      @change="changeToop($event)"
      ccept="image/png, image/jpg, image/jpeg"
    />
  </div>
</template>
<script>
import { reactive, toRefs, onMounted, inject } from "vue";

export default {
  props: ["msg"],
  setup(props, ctx) {
    const state = reactive({
      myMsg: inject("msg"),
    });
    function Id(id) {
      return document.getElementById(id);
    }
    function changeToop(e) {
      var file = Id("file");
      //传递选择的文件给父组件
      ctx.emit('onBack',e.target.files[0]);
      if (file.value == "") {
        //设置默认图片
        Id("myimg").src = require("@/assets/logo.png");
      } else {
        preImg("file", "myimg");
      }
    }
    //获取input[file]图片的url Important
    function getFileUrl(fileId) {
      var url;
      var file = Id(fileId);
      url = window.URL.createObjectURL(file.files.item(0));
      return url;
    }
    //读取图片后预览
    function preImg(fileId, imgId) {
      var imgPre = Id(imgId);
      imgPre.src = getFileUrl(fileId);
    }
    return { ...toRefs(state), changeToop };
  },
};
</script>
<style lang="less" scoped>
.uploader {
  width: 100px;
  height: 100px;
  .myimg {
    width: 100px;
    height: 100px;
    border-radius: 10px;
  }
}
</style>
